<?php
/**
 * CSV操作类
 *
 * CSV文件的读取及生成
 * @author Mo yi <root@imoi.cn>
 * @link   http://www.imoi.cn
 * @copyright Copyright &copy; 2010-2012 DuoLam Software LLC
 * @license http://www.imoi.cn/license/
 * @version $Id: dpCsv.php 1.1 2011-12-18 12:10:01Z tommy $
 * @package web.helper
 * @since 1.0
 */

class dpCsv
{

    /**
     * 将CSV文件转化为数组
     *
     * @access public
     * @param string $file_name csv文件名(路径)
     * @param string $delimiter 单元分割符(逗号或制表符)
     * @return array
     */
    public static function readCsv($file_name, $delimiter = ",")
	{

        //参数分析
        if (!$file_name)
            return false;

        //读取csv文件内容
        $handle       = fopen($file_name, 'r');
        $output_array = array();
        $row          = 0;
        while ($data = fgetcsv($handle, 1000, $delimiter)) {
            $num = count($data);
            for ($i = 0; $i < $num; $i ++)
                $output_array[$row][$i] = $data[$i];
            $row++;
        }
        fclose($handle);

        return $output_array;
    }

    /**
     * 生成csv文件
     *
     * @access public
     * @param string $file_name 所要生成的文件名
     * @param array $data csv数据内容, 注:本参数为二维数组
     * @return void
     */
    public static function makeCsv($file_name, $data)
	{
        //参数分析
        if (!$file_name || !$data || !is_array($data)) return false;
        if (stripos($file_name, '.csv') === false) $file_name .= '.csv';
 
        //分析$data内容
        $content = '';
        foreach ($data as $lines) $content .= implode(",", $lines) . "\n";

        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
		header('Expires:0');
		header('Pragma:public');
		header("Cache-Control: public");
		header("Content-type:text/csv");
        header("Content-Disposition:attachment;filename=" . $file_name);

        echo $content;
    }
}
?>